package com.tensquare.user.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import enums.ResultEnum;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import com.tensquare.user.pojo.User;
import com.tensquare.user.service.UserService;

import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import util.JwtUtil;
import util.ResultUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * 控制器层
 *
 * @author Administrator
 */
@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;


    /**
     * 增加关注数
     *
     * @param userid
     * @param x
     */
    @PostMapping("/incfollow/{userid}/{x}")
    public void incFollowcount(@PathVariable String userid, @PathVariable Integer x) {
        userService.incFollowcount(userid, x);
    }

    /**
     * 增加粉丝数
     *
     * @param userid 用户ID
     * @param x      粉丝数
     */
    @PostMapping("/incfans/{userid}/{x}")
    public void incFanscount(@PathVariable String userid, @PathVariable Integer x) {
        userService.incFanscount(userid, x);
    }


    /**
     * 用户登录
     *
     * @param userin 用户
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody User userin) {
        User user = userService.findByMobileAndPassword(userin.getMobile(), userin.getPassword());

        return Optional.ofNullable(user)
                .map(u -> {
                    String jws = jwtUtil.createJWS(user.getId(), user.getNickname(), "user");
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("token", jws);
                    map.put("name", u.getNickname());
                    map.put("avatar", u.getAvatar());
                    return ResultUtil.success(map);
                }).orElse(ResultUtil.valueOf(ResultEnum.LOGIN_ERROR));
    }

    /**
     * 用户注册
     *
     * @param user
     * @param code
     * @return
     */
    @PostMapping("/register/{code}")
    public Result register(@RequestBody User user, @PathVariable String code) {
        userService.add(user, code);
        return ResultUtil.successMsg("注册成功!");
    }


    /**
     * 调用发送短信验证码接口
     *
     * @param mobile
     * @return
     */
    @PostMapping("/sendsms/{mobile}")
    public Result sendsms(@PathVariable String mobile) {
        userService.sendSms(mobile);
        return ResultUtil.successMsg("发送成功");
    }

    /**
     * 查询全部数据
     *
     * @return
     */
    @GetMapping
    public Result findAll() {
        return new Result(true, StatusCode.OK, "查询成功", userService.findAll());
    }

    /**
     * 根据ID查询
     *
     * @param id ID
     * @return
     */
    @GetMapping("/{id}")
    public Result findById(@PathVariable String id) {
        return new Result(true, StatusCode.OK, "查询成功", userService.findById(id));
    }


    /**
     * 分页+多条件查询
     *
     * @param searchMap 查询条件封装
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @RequestMapping(value = "/search/{page}/{size}", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Page<User> pageList = userService.findSearch(searchMap, page, size);
        return new Result(true, StatusCode.OK, "查询成功", new PageResult<User>(pageList.getTotalElements(), pageList.getContent()));
    }

    /**
     * 根据条件查询
     *
     * @param searchMap
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap) {
        return new Result(true, StatusCode.OK, "查询成功", userService.findSearch(searchMap));
    }

    /**
     * 增加
     *
     * @param user
     */
    @RequestMapping(method = RequestMethod.POST)
    public Result add(@RequestBody User user) {
        userService.add(user);
        return new Result(true, StatusCode.OK, "增加成功");
    }

    /**
     * 修改
     *
     * @param user
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public Result update(@RequestBody User user, @PathVariable String id) {
        user.setId(id);
        userService.update(user);
        return new Result(true, StatusCode.OK, "修改成功");
    }

    /**
     * 删除
     *
     * @param id
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable String id, HttpServletRequest request) {

        Claims claims = (Claims) request.getAttribute("admin_claims");
        return Optional.ofNullable(claims).map(c -> {
            userService.deleteById(id);
            return ResultUtil.successMsg("删除成功！");
        }).orElse(ResultUtil.valueOf(ResultEnum.ACCESS_ERROR));

//        if (claims == null) {
//            return ResultUtil.valueOf(ResultEnum.ACCESS_ERROR);
//        }
//        userService.deleteById(id);
//        return ResultUtil.successMsg("删除成功！");
    }

}
